#!/bin/bash

all_services=(
    calico-node
    coredns
    etcd
    kube-apiserver
    kube-controller-manager
    kube-flannel
    kube-proxy
    kube-scheduler
    metrics-server
    rke2-ingress-nginx-controller
)

export NUM_SERVERS=1
export NUM_AGENTS=1
export WAIT_SERVICES="${all_services[@]}"

start-test() {
    #docker exec $(cat $TEST_DIR/servers/1/metadata/name) check-config || true
    use-nodelocal-DNSCache
    verify-valid-versions $(cat $TEST_DIR/servers/1/metadata/name)
    verify-airgap-images $(cat $TEST_DIR/{servers,agents}/*/metadata/name)
}
export -f start-test

# -- check for changes to the airgap image list
# -- this currently only checks imags for the default CNI and charts
verify-airgap-images() {
    local expected="$TEST_DIR/logs/images-expected.txt"
    local actual="$TEST_DIR/logs/images-actual.txt"
    docker exec $(cat $TEST_DIR/servers/1/metadata/name) cat /images.txt | sort -u >$expected

    for name in $@; do
        docker exec $name crictl images -o json \
            | jq -r '.images[].repoTags[0] | select(. != null)'
    done | sort -u >$actual

    if ! diff $expected $actual; then
        echo '[ERROR] Failed airgap image check'
        return 1
    fi
    return 0
}
export -f verify-airgap-images


# -- Enable the nodelocal DNSCache so that its images are used
use-nodelocal-DNSCache() {
    local DNS_nodeCache_manifest='scripts/airgap/dnsNodeCache-test.yaml'
    kubectl apply -f $DNS_nodeCache_manifest
    wait-for-services node-cache
}
export -f use-nodelocal-DNSCache

# --- create a basic cluster and check for valid versions
LABEL=BASICS run-test
